﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Net;
using System.Reflection;
using System.Text;

namespace 公众号发送信息
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("调用微信公众号发送信息");
            new Program().Init();
        }
        
        public async void Init()
        {
            Console.WriteLine("初始化");
            // 假设GetAccessToken是封装好的调用接口方法
            string appId = "wxfb5c41b59ec631f3", appSecret = "49543264146be938b937c37d63f4a0a6";
            //var accessToken =await GetAccessToken(appId, appSecret);
            //// 使用示例
            //var success = SendMessageToUserAsync(accessToken, "USER_ID", "Hello, this is a test message.");
            var token = File.ReadAllText("D:\\tmp\\token.txt");
            var success = SendMessageToUserAsync(token,"123","111");
        }

        public async Task<string> GetAccessToken(string appId, string appSecret)
        {
            var url = $"https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={appId}&secret={appSecret}";
            using (var client = new HttpClient())
            {
                try
                {
                    HttpResponseMessage response = client.GetAsync(url).Result;
                    if (response.IsSuccessStatusCode)
                    {
                        var result = await response.Content.ReadAsStringAsync();
                        dynamic jsonResult = JObject.Parse(result);
                        var wxToken = jsonResult.access_token.ToString();
                        if (!string.IsNullOrEmpty(wxToken))
                        {
                            return jsonResult.access_token;
                        }
                        else
                        {
                            throw new Exception($"获取AccessToken失败，错误代码：{jsonResult.errcode}，错误信息：{jsonResult.errmsg}");
                        }
                    }
                    else
                    {
                        throw new Exception($"获取AccessToken请求失败，HTTP状态码：{response.StatusCode}");
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"获取AccessToken时发生错误：{ex.Message}");
                    throw;
                }
            }
        }

        public async Task<bool> SendMessageToUserAsync(string accessToken, string userId, string messageText)
        {
            var url = $"https://qyapi.weixin.qq.com/cgi-bin/message/send/template?access_token={accessToken}";
            var requestBody = new WxSendMessage()
            {
                 touser="OPENID",
                 template_id="ngqIpbwh8bUfcSsECmogfXcV14J0tQlEpBO27izEYtY",
                 url="",
                 miniprogram = new Miniprogram(){},
                 client_msg_id="MSG_000001",
                 data = new WxData()
                 {
                     keyword1 = new WxValue() {  value="巧克力" },
                     keyword2 = new WxValue() {  value="39.8元" },
                     keyword3 = new WxValue() {  value="2014年9月22日" },
                 }
                 
            };
            var sendData = JsonConvert.SerializeObject(requestBody);
            Console.WriteLine(JsonConvert.SerializeObject(requestBody));
            using (var client = new HttpClient())
            {
                var content = new StringContent(sendData, Encoding.UTF8, "application/json");
                var response = client.PostAsync(url, content).Result;
                if (response.IsSuccessStatusCode)
                {
                    var result = await response.Content.ReadAsStringAsync();
                    Console.WriteLine($"[微信发送消息返回内容]：{result}");
                    dynamic jsonResult = JObject.Parse(result);
                    if (jsonResult.errcode == 0)
                    {
                        return true;
                    }
                }
                return false;
            }
        }

        public async Task<RequestProxyRespond> Proxy(RequestProxy request)
        {
            var client = new HttpClient();
            var message = new HttpRequestMessage(request.MethodType.ToUpper() switch
            {
                "GET" => HttpMethod.Get,
                "POST" => HttpMethod.Post,
                _ => HttpMethod.Post
            }, request.Url);
            foreach (var item in request.Headers)
            {
                message.Headers.Add(item.Key, item.Value);
            }
            if (message.Method != HttpMethod.Get)
                message.Content = new StringContent(request.Body);
            HttpResponseMessage respond;
            try
            {
                respond = await client.SendAsync(message);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"请求出错：{ex.Message}");
                throw;
            }
            var result = await respond.Content.ReadAsStringAsync();
            if (!respond.IsSuccessStatusCode)
            {
                Console.WriteLine($"Proxy is success response: {result}");
            }
            return new RequestProxyRespond
            {
                Status = respond.StatusCode,
                Respond = result
            };
        }
    }
    class WxSendMessage
    {
        public string touser { get; set; }
        public string template_id { get; set; }
        public string url { get; set; }
        public Miniprogram  miniprogram { get; set; }
        public string client_msg_id { get; set; }
        public WxData data { get; set; }

    }
    public class Miniprogram
    {
        public string appid { get; set;}
        public string pagepath { get; set;}
    }
    public class WxData
    {
        public WxValue keyword1 { get; set;}
        public WxValue keyword2 { get; set;}
        public WxValue keyword3 { get; set;}
    }
    public class WxValue
    {
        public string value { get; set; }
    }
}
